<template>
  <div ref="chartContainer" class="china-map-container">
    <div ref="chartRef" class="china-map"></div>
  </div>
</template>
<script lang="ts" setup>
import { mapDataItemType, toolTipDataType } from '@/views/platform/types/index';
import useResize from '@/hooks/useResize';
import img3 from '@/assets/images/platform/arrow-left.png';
import china from '@/assets/platform/json/china.json';
import beijing from '@/assets/platform/json/beijing.json';
import guangxi from '@/assets/platform/json/guangxi.json';
import hubei from '@/assets/platform/json/hubei.json';
import liaoning from '@/assets/platform/json/liaoning.json';
import shanxi from '@/assets/platform/json/shanxi.json';
import sichuan from '@/assets/platform/json/sichuan.json';
import hebei from '@/assets/platform/json/hebei.json';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
let mapName = 'china';
let layoutSize = '220%';
let toolTipData: toolTipDataType[] = [];
let lineGap = 0;
let rectSymbolOffset = [];
let chartInstance = null;
const chartContainer = ref<HTMLElement | null>(null);
const chartData = ref();
const chartRef = ref();
interface propsType {
  from?: string;
  excellentWidthAndHeight: {
    width: number;
    height: number;
  };
  mapData: { [key: string]: mapDataItemType };
}
const props = defineProps<propsType>();
const provinceArr = ['北京市', '辽宁省', '四川省', '贵州省', '西藏自治区', '福建省'];
const emit = defineEmits(['mouseover']);
const downArrowImgUrl = ref('');

let img2 =
  'image://';
let imgClone =
  '';
/**
 * 提示信息坐标集合
 * coords:[
 *  线条起始点坐标,
 *  提示框左下坐标
 * ]
 *
 * coords:[地图x轴，地图y轴]
 * x轴值越大越靠右，y值越大越靠上
 *
 */
let LableData = {
  'china': [
    {
      name: '辽宁',
      coords: [
        [123.1238, 42.1216],
        [124.1238, 45.1216]
      ]
    },
    //中国地图显示的是市区，北京显示海淀和丰台
    {
      name: '海淀区',
      coords: [
        [116.3, 40],
        [110.24, 45.55]
      ]
    },
    {
      name: '丰台区',
      coords: [
        [116.2, 39.85],
        [123.4219, 45.4189]
      ]
    },
    {
      name: '湖北',
      coords: [
        [114.3896, 30.6628],
        [118.3896, 28.6628]
      ]
    },
    {
      name: '陕西',
      coords: [
        [109.1162, 34.2004],
        [100, 40]
      ]
    },
    {
      name: '四川',
      coords: [
        [103.9526, 30.7617],
        [91.5526, 33.7617]
      ]
    },
    {
      name: '广西',
      coords: [
        [108.479, 23.1152],
        [114.479, 20.1152]
      ]
    },
    {
      name: '河北',
      coords: [
        [114.4995, 38.1006],
        [120.479, 37.5152]
      ]
    }
  ],
  'liaoning': [
    {
      name: '沈阳',
      coords: [
        [123.1238, 42.1216],
        [123.3238, 42.4216]
      ]
    }
  ],
  'sichuan': [
    {
      name: '成都市',
      coords: [
        [103.9526, 30.7617],
        [104.24, 31.5]
      ]
    }
  ],
  'guangxi': [
    {
      name: '柳州市',
      coords: [
        [109.5, 24.56],
        [110, 25]
      ]
    }
  ],
  'hubei': [
    {
      name: '荆州市',
      coords: [
        [112.5, 30],
        [112.7, 30.3]
      ]
    }
  ],
  'shanxi': [
    {
      name: '西安市',
      coords: [
        [109.1162, 34.2004],
        [109.5162, 34.7]
      ]
    }
  ],
  'beijing': [
    {
      name: '丰台区',
      coords: [
        [116.2, 39.85],
        [116.5, 39.7]
      ]
    },
    {
      name: '海淀区',
      coords: [
        [116.3, 40],
        [116.5, 40.25]
      ]
    }
  ],
  'hebei': [
    {
      name: '河北易县',
      coords: [
        [115.4972008, 39.3527366],
        [115.53, 39.7]
      ]
    }
  ]
};
let geoCoordMap = {
  '黑龙江': [127.9688, 45.368],
  '内蒙古': [110.3467, 41.4899],
  '吉林': [125.8154, 44.2584],
  '北京市': [116.4551, 40.2539],
  '海淀区': [116.3, 40],
  '丰台区': [116.2, 39.85],
  '辽宁': [123.1238, 42.1216],
  '沈阳': [123.1238, 42.1216],
  '河北': [114.4995, 38.1006],
  '河北易县': [115.4972008, 39.3527366], //河北省保定市易县
  '天津': [117.4219, 39.4189],
  '山西': [112.3352, 37.9413],
  '陕西': [109.1162, 34.2004],
  '西安市': [109.1162, 34.2004],
  '甘肃': [103.5901, 36.3043],
  '宁夏': [106.3586, 38.1775],
  '青海': [101.4038, 36.8207],
  '新疆': [87.611053, 43.828171],
  '西藏': [91.117212, 29.646922],
  '四川': [103.9526, 30.7617],
  '成都市': [103.9526, 30.7617],
  '重庆': [108.384366, 30.439702],
  '山东': [117.1582, 36.8701],
  '河南': [113.4668, 34.6234],
  '江苏': [118.8062, 31.9208],
  '安徽': [117.29, 32.0581],
  '湖北': [114.3896, 30.6628],
  '荆州市': [112.5, 30],
  '浙江': [119.5313, 29.8773],
  '福建': [119.4543, 25.9222],
  '江西': [116.0046, 28.6633],
  '湖南': [113.0823, 28.2568],
  '贵州': [106.6992, 26.7682],
  '云南': [102.9199, 25.4663],
  '广东': [113.12244, 23.009505],
  '广西': [108.479, 23.1152],
  '柳州市': [109.5, 24.56],
  '海南': [110.3893, 19.8516],
  '台湾': [120.702967, 24.123621],
  '上海': [121.4648, 31.2891]
};
function initChinaParam() {
  mapName = 'china';
  layoutSize = '220%';
  lineGap = 1.5;
  rectSymbolOffset = [0, -40];

  let tmpToolTipData = [
    {
      name: '海淀区',
      namestr: 'beijing',
      areas: ['永定路地区'],
      ident: props.mapData['BJ_YDL']
    },
    {
      name: '丰台区',
      namestr: 'beijing',
      areas: ['云岗地区'],
      ident: props.mapData['BJ_YG']
    },
    {
      name: '湖北',
      namestr: 'hubei',
      areas: ['湖北地区'],
      secTitle: '南湖公司',
      ident: props.mapData['HU_BEI']
    },
    {
      name: '陕西',
      namestr: 'shanxi',
      areas: ['西安地区'],
      ident: props.mapData['XI_AN']
    },
    {
      name: '四川',
      namestr: 'sichuan',
      areas: ['成都地区'],
      ident: props.mapData['CHENG_DU']
    },
    {
      name: '广西',
      namestr: 'guangxi',
      areas: ['柳州地区'],
      secTitle: '八〇一厂',
      ident: props.mapData['LIU_ZHOU']
    },
    // {
    //   name: '辽宁',
    //   namestr: 'liaoning',
    //   areas: ['沈阳'],
    //   secTitle: '一三九厂、一 一九厂',
    //   ident: props.mapData['SHEN_YANG']
    // },
    {
      name: '河北',
      namestr: 'hebei',
      areas: ['河北地区'],
      secTitle: '二十三所、二八三厂',
      ident: props.mapData['HEBEI_YIXIAN']
    }
  ];

  //toolTipData拼接labelData
  toolTipData = tmpToolTipData.map((item) => {
    let labelItem = LableData['china'].find((item1) => item1.name == item.name);
    if (labelItem) {
      return { ...item, ...labelItem };
    }
  });
}

function convertData(data) {
  var res = [];
  for (var i = 0; i < data.length; i++) {
    var geoCoord = geoCoordMap[data[i].name];
    if (geoCoord) {
      res.push({
        name: data[i].name,
        value: geoCoord.concat(data[i].value)
      });
    }
  }
  return res;
}

// 柱状体的主干
function lineData(mapName) {
  if (mapName != 'china') {
    return [];
  }
  const colorList = ['#D88BFF', '#5abead', '#66FFFF', '#48D5FF', '#FFE73D', '#66FFFF'];
  const lineOption = [];
  const lastPoint = {
    name: '海淀区',
    value: [116.3, 40],
    lineStyle: {
      color: '#FF6C66'
    }
  };
  toolTipData.map((item, index) => {
    // console.log(item);

    let lineItem = { ...item };
    // lineItem.lineStyle = { color: colorList[index % colorList.length] };
    lineItem.lineStyle = { color: '#48D5FF' };

    lineItem.coords = [geoCoordMap[item.name], lastPoint.value];
    lineOption.push(lineItem);
  });
  console.log(lineOption);

  return lineOption;
}

// 柱状体的顶部
function scatterData() {
  return toolTipData.map((item) => {
    return [geoCoordMap[item.name][0], geoCoordMap[item.name][1] + 2, item];
  });
}

const infoClass = `
    width: 274px;
    height: 115px;
    padding-top: 10px;
    background: rgba(35, 132, 221, 0.75);`;
const infoItemClass = `display: flex;
    justify-content: space-between;
    width: 222px;
    height: 26px;
    line-height: 30px;
    margin: 4px auto;
    padding: 0 20px;
    background: rgba(35, 132, 221, 0.85);
    color: #fff`;

let tooltip = {
  trigger: 'item',
  backgroundColor: 'transparent',
  borderWidth: 0,
  formatter: function (params) {
    if (params.seriesIndex === 2) {
      return `
          <div style="${infoClass}">
            <div style="${infoItemClass}"><span>单位数量</span><span>${params.data.ident?.orgCount}</span></div>
            <div style="${infoItemClass}"><span>主机数量</span><span>${params.data.ident?.assetCount}</span></div>
            <div style="${infoItemClass}"><span>主机告警数量</span><span>${params.data.ident?.virusCount + params.data.ident?.violationCount + params.data.ident?.exceptionCount}</span></div>
          </div>`;
      // <div style="${infoItemClass}"><span>当月事件数量</span><span>${params.data.ident?.eventCount}</span></div>
      //  <div style="${infoItemClass}"><span>网络流量</span><span>${params.data.ident?.netTrafficCount}</span></div>
      // <div style="${infoItemClass}"><span>网络会话</span><span>${params.data.ident?.neteSessionCount}</span></div>
    }
  }
};

//初始化图表
const initChart = () => {
  //注册echart实例
  chartInstance = proxy?.$echarts.init(chartRef.value);
  //注册地图，这个特别重要
  proxy?.$echarts.registerMap('china', china);
  proxy?.$echarts.registerMap('beijing', beijing);
  proxy?.$echarts.registerMap('guangxi', guangxi);
  proxy?.$echarts.registerMap('hubei', hubei);
  proxy?.$echarts.registerMap('liaoning', liaoning);
  proxy?.$echarts.registerMap('shanxi', shanxi);
  proxy?.$echarts.registerMap('sichuan', sichuan);
  proxy?.$echarts.registerMap('hebei', hebei);

  const initOption = {
    tooltip
  };
  chartInstance.setOption(initOption);

  chartInstance.on('click', (e) => {
    if (mapName === 'china' && e.seriesName === 'tipBox') {
      let tmpToolTipData: toolTipDataType[];
      switch (e.data.namestr) {
        case 'beijing':
          mapName = 'beijing';
          layoutSize = '150%';
          lineGap = 0.1;
          rectSymbolOffset = [0, 500];
          tmpToolTipData = [
            {
              name: '海淀区',
              areas: ['永定路地区'],
              ident: props.mapData['BJ_YDL']
            },
            {
              name: '丰台区',
              areas: ['云岗地区'],
              ident: props.mapData['BJ_YG']
            }
          ];
          toolTipData = tmpToolTipData.map((item) => {
            let labelItem = LableData['beijing'].find((item1) => item1.name == item.name);
            if (labelItem) {
              return { ...item, ...labelItem };
            }
          });

          break;
        case 'guangxi':
          mapName = 'guangxi';

          lineGap = 0.5;
          rectSymbolOffset = [0, 120];
          tmpToolTipData = [
            {
              name: '柳州市',
              areas: ['柳州地区'],
              secTitle: '八〇一厂',
              ident: props.mapData['LIU_ZHOU']
            }
          ];
          toolTipData = tmpToolTipData.map((item) => {
            let labelItem = LableData['guangxi'].find((item1) => item1.name == item.name);
            if (labelItem) {
              return { ...item, ...labelItem };
            }
          });

          break;
        case 'hubei':
          mapName = 'hubei';

          lineGap = 0.5;
          rectSymbolOffset = [0, 120];
          tmpToolTipData = [
            {
              name: '荆州市',
              areas: ['湖北地区'],
              secTitle: '南湖公司',
              ident: props.mapData['HU_BEI']
            }
          ];
          toolTipData = tmpToolTipData.map((item) => {
            let labelItem = LableData['hubei'].find((item1) => item1.name == item.name);
            if (labelItem) {
              return { ...item, ...labelItem };
            }
          });

          break;
        case 'liaoning':
          mapName = 'liaoning';

          lineGap = 0.3;
          rectSymbolOffset = [0, 150];
          tmpToolTipData = [
            {
              name: '沈阳',
              areas: ['沈阳地区'],
              secTitle: '一三九厂、一 一九厂',
              ident: props.mapData['SHEN_YANG']
            }
          ];
          toolTipData = tmpToolTipData.map((item) => {
            let labelItem = LableData['liaoning'].find((item1) => item1.name == item.name);
            if (labelItem) {
              return { ...item, ...labelItem };
            }
          });

          break;
        case 'shanxi':
          mapName = 'shanxi';

          lineGap = 0.5;
          rectSymbolOffset = [0, 70];
          tmpToolTipData = [
            {
              name: '西安市',
              areas: ['西安地区'],
              ident: props.mapData['XI_AN']
            }
          ];
          toolTipData = tmpToolTipData.map((item) => {
            let labelItem = LableData['shanxi'].find((item1) => item1.name == item.name);
            if (labelItem) {
              return { ...item, ...labelItem };
            }
          });

          break;
        case 'sichuan':
          mapName = 'sichuan';

          lineGap = 0.5;
          rectSymbolOffset = [0, 70];
          tmpToolTipData = [
            {
              name: '成都市',
              areas: ['成都地区'],
              ident: props.mapData['CHENG_DU']
            }
          ];
          toolTipData = tmpToolTipData.map((item) => {
            let labelItem = LableData['sichuan'].find((item1) => item1.name == item.name);
            if (labelItem) {
              return { ...item, ...labelItem };
            }
          });

          break;
        case 'hebei':
          mapName = 'hebei';

          lineGap = 0.5;
          rectSymbolOffset = [0, 70];
          tmpToolTipData = [
            {
              name: '河北易县',
              areas: ['河北地区'],
              secTitle: '二十三所、二三八厂',
              ident: props.mapData['HEBEI_YIXIAN']
            }
          ];
          toolTipData = tmpToolTipData.map((item) => {
            let labelItem = LableData['hebei'].find((item1) => item1.name == item.name);
            if (labelItem) {
              return { ...item, ...labelItem };
            }
          });

          break;
        default:
          console.log('没有对应城市');
          return;
      }
      updateChart(mapName);
    }
  });
};

function getChartData(outData) {
  chartData.value = outData;
  updateChart();
}

//更新图表数据
const updateChart = (mapName = 'china') => {
  if (mapName == 'china') {
    initChinaParam();
  }
  // 定义一个变量来存储动态的 geo 布局配置
  let geoLayoutConfig: any;

  // 判断是否是中国地图
  if (mapName === 'china') {
    // 如果是中国地图，使用能够拉伸并铺满容器的配置
    geoLayoutConfig = {
      left: 0,
      top: 0,
      right: 0,
      bottom: 0
    };
    // 注意：当使用 left/top/right/bottom 时，不再需要 layoutCenter, layoutSize, zoom, aspectScale
  } else {
    // 如果是下钻的省份地图，保留原有的布局方式
    geoLayoutConfig = {
      layoutCenter: ['51%', '46%'], // 位置
      layoutSize, // 大小 (这个变量在下钻时会被更新)
      zoom: 0.65,
      aspectScale: 1 // 保持省份地图的原始宽高比
    };
  }

  //为了避免报错 The lines series must have a coordinate system.
  //所以不把series分离到initOption
  const dataOption = {
    geo: [
      {
        // ...geoLayoutConfig,
        id: 'geo1',
        show: true,
        map: mapName,
        roam: false,
        label: {
          show: false,
          textStyle: {
            color: '#fff'
          },
          emphasis: {
            show: true,
            textStyle: {
              color: '#fff'
            }
          }
        },
        itemStyle: {
          areaColor: {
            type: 'linear',
            x: 1200,
            y: 0,
            x2: 0,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(3,27,78,0.75)' // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'rgba(58,149,253,0.75)' // 50% 处的颜色
              }
            ],
            global: true // 缺省为 false
          },
          borderColor: '#c0f3fb',
          borderWidth: 1,
          shadowColor: '#8cd3ef',
          shadowOffsetY: 10,
          shadowBlur: 120,
          emphasis: {
            areaColor: 'rgba(0,254,233,0.6)'
            // borderWidth: 0
          }
        }
        // regions: [
        //   {
        //     // 隐藏南海诸岛,因为顶层已经添加过了
        //     name: '南海诸岛',
        //     value: 0,
        //     itemStyle: {
        //       opacity: 0 // 为 0 时不绘制该图形
        //     },
        //     label: {
        //       show: false
        //     }
        //   }
        // ]
      },
      {
        // ...geoLayoutConfig,
        id: 'geo2',
        type: 'map',
        map: mapName,
        zlevel: -1,
        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 1,
          borderColor: 'rgba(58,149,253,0.8)',
          shadowColor: 'rgba(172, 122, 255,0.5)',
          shadowOffsetY: 5,
          shadowBlur: 15,
          areaColor: 'rgba(5,21,35,0.1)'
        },
        regions: [
          {
            // 隐藏南海诸岛,因为顶层已经添加过了
            name: '南海诸岛',
            value: 0,
            itemStyle: {
              opacity: 0 // 为 0 时不绘制该图形
            },
            label: {
              show: false
            }
          }
        ]
      },
      {
        // ...geoLayoutConfig,
        id: 'geo3',
        type: 'map',
        map: mapName,
        zlevel: -2,

        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 1,
          borderColor: 'rgba(58,149,253,0.6)',
          shadowColor: 'rgba(65, 214, 255,1)',
          shadowOffsetY: 5,
          shadowBlur: 15,
          areaColor: 'transpercent'
        },
        regions: [
          {
            // 隐藏南海诸岛,因为顶层已经添加过了
            name: '南海诸岛',
            value: 0,
            itemStyle: {
              opacity: 0 // 为 0 时不绘制该图形
            },
            label: {
              show: false
            }
          }
        ]
      },
      {
        // ...geoLayoutConfig,
        id: 'geo4',
        type: 'map',
        map: mapName,
        zlevel: -3,
        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 1,
          borderColor: 'rgba(58,149,253,0.4)',
          shadowColor: 'rgba(58,149,253,1)',
          shadowOffsetY: 15,
          shadowBlur: 10,
          areaColor: 'transpercent'
        },
        regions: [
          {
            // 隐藏南海诸岛,因为顶层已经添加过了
            name: '南海诸岛',
            value: 0,
            itemStyle: {
              opacity: 0 // 为 0 时不绘制该图形
            },
            label: {
              show: false
            }
          }
        ]
      },
      {
        // ...geoLayoutConfig,
        id: 'geo5',
        type: 'map',
        map: mapName,
        zlevel: -4,

        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 5,
          borderColor: 'rgba(5,9,57,0.8)',
          shadowColor: 'rgba(29, 111, 165,0.8)',
          shadowOffsetY: 15,
          shadowBlur: 10,
          areaColor: 'rgba(5,21,35,0.1)'
        },
        regions: [
          {
            // 隐藏南海诸岛,因为顶层已经添加过了
            name: '南海诸岛',
            value: 0,
            itemStyle: {
              opacity: 0 // 为 0 时不绘制该图形
            },
            label: {
              show: false
            }
          }
        ]
      }
    ],
    series: [
      //飞线图
      {
        type: 'lines',
        coordinateSystem: 'geo',
        z: 100,
        effect: {
          show: true,
          period: 8, // 箭头指向速度，值越小速度越快
          trailLength: 0.4, // 特效尾迹长度[0,1]值越大，尾迹越长重
          symbol: 'arrow', // 箭头图标
          symbolSize: 5 // 图标大小
        },
        lineStyle: {
          color: '#1DE9B6',
          width: 1, // 线条宽度
          opacity: 0.1, // 尾迹线条透明度
          curveness: 0.3 // 尾迹线条曲直度
        },
        data: lineData(mapName)
      },
      {
        type: 'effectScatter',
        coordinateSystem: 'geo',
        showEffectOn: 'render',
        z: 90,
        rippleEffect: {
          period: 12,
          scale: 4,
          brushType: 'fill'
        },
        label: {
          formatter: '{b}',
          position: 'top',
          offset: [0, -10],
          color: '#fff',
          show: false,
          fontSize: 12
        },
        itemStyle: {
          color: (value) => {
            return value.data.lineStyle?.color || '#16ffff';
          },
          shadowBlur: 10,
          shadowColor: '#333'
        },
        symbolSize: 8,
        data: convertData(toolTipData)
      },
      //提示框位置
      {
        name: 'tipBox',
        type: 'lines',
        coordinateSystem: 'geo',
        zlevel: 3,
        symbol: 'circle',
        symbolSize: [5, 5],
        color: '#ff8003',
        opacity: 1,
        label: {
          show: true,
          padding: [10, 20],
          color: '#fff',
          backgroundColor: {
            image: imgClone
          },
          borderColor: '#aee9fb',
          borderWidth: 1,
          borderRadius: 6,
          formatter(params) {
            // console.log(params.data);

            let text = '';
            if (Array.isArray(params.data.areas) && params.data.areas.length > 0) {
              text += `{tTitle|${params.data.areas[0]}}\n`;
            } else {
              text += `{tTitle|${params.data.name}}\n`;
            }

            if (params.data.secTitle) {
              text += `{tSubTitle|${params.data.secTitle}}\n`;
            }
            text += `主机数量：${params.data.ident?.assetCount}\n`;
            text += `主机告警数量：${params.data.ident?.virusCount + params.data.ident?.violationCount + params.data.ident?.exceptionCount}`;

            return text;
          },
          textStyle: {
            align: 'left',
            lineHeight: 20
          },
          rich: {
            'tTitle': {
              align: 'center'
            },
            tSubTitle: {
              align: 'center'
            }
          }
        },
        lineStyle: {
          type: 'solid',
          color: '#FFE73D',
          width: 0.5,
          opacity: 1
        },
        data: toolTipData
      }
    ],
    //显示回归箭头
    graphic: {
      elements: [
        {
          type: 'image',
          left: 30,
          bottom: 80,
          style: {
            opacity: mapName === 'china' ? 0 : 1,
            width: 30,
            height: 30,
            image: img3,
            zIndex: 999
          },
          onclick: function () {
            updateChart();
          }
        }
      ]
    }
  };
  chartInstance.setOption(dataOption);
  // adjustMapSize();
  adjustMapSizeByPosition();
};

// onMounted(() => {
//   initChart();
// });

watch(
  () => props.mapData,
  () => {
    if (chartInstance) {
      getChartData(props.mapData);
    } else {
      nextTick(() => {
        initChart();
        getChartData(props.mapData);
      });
    }
  },
  {
    deep: true,
    immediate: true
  }
);

// 调整地图大小和位置
function adjustMapSize() {
  if (!chartInstance || !chartContainer.value) {
    console.log('99');
    return;
  }

  const containerWidth = chartContainer.value.clientWidth;
  const containerHeight = chartContainer.value.clientHeight;
  console.log(`${containerWidth}-${containerHeight}`);

  let excellentWidth = props.excellentWidthAndHeight.width || 930;
  let excellentHeight = props.excellentWidthAndHeight.height || 660;

  if (mapName == 'china') {
    // 计算缩放比例 - 基于原始设计尺寸930x660
    const widthRatio = containerWidth / excellentWidth;
    const heightRatio = containerHeight / excellentHeight;
    const scale = Math.min(widthRatio, heightRatio) * 0.95; // 稍微缩小一点留出边距
    console.log('缩放比例', scale);

    // 更新所有geo配置
    const option = chartInstance.getOption();

    if (Array.isArray(option.geo)) {
      option.geo.forEach((geo: any, index: number) => {
        // 根据索引调整不同geo的位置
        const xPosition = index === 0 ? '30%' : '70%';
        geo.layoutCenter = ['50%', `${50 + index}%`];
        geo.layoutSize = `${140 * scale}%`;
        geo.zoom = scale;
      });

      chartInstance.setOption({
        geo: option.geo
      });
    }
  } else {
    console.log('77');

    // 更新所有geo配置
    const option = chartInstance.getOption();

    if (Array.isArray(option.geo)) {
      option.geo.forEach((geo: any, index: number) => {
        // 根据索引调整不同geo的位置
        const xPosition = index === 0 ? '30%' : '70%';
        geo.layoutCenter = ['50%', `${50 + index}%`];
        geo.layoutSize = `100%`;
      });

      chartInstance.setOption({
        geo: option.geo
      });
    }
  }
}

function adjustMapSizeByPosition() {
  if (!chartInstance || !chartContainer.value) {
    return;
  }
  // 定义一个变量来存储动态的 geo 布局配置
  let geoLayoutConfig: any;
  if (mapName == 'china') {
    geoLayoutConfig = {
      left: 0,
      top: 0,
      right: 0,
      bottom: 0
    };
    // 更新所有geo配置
    const option = chartInstance.getOption();

    if (Array.isArray(option.geo)) {
      option.geo.forEach((geo: any, index: number) => {
        // 如果是中国地图，使用能够拉伸并铺满容器的配置
        // 根据索引调整不同geo的位置
        geo.left = 0;
        geo.right = 0;
        geo.bottom = 0;
        geo.top = `${index}%`;
        geo.layoutCenter = 'auto';
        // geo.layoutCenter = ['51%', `${46 + index * 0.5}%`]; // 位置
        geo.layoutSize = 'auto';
        geo.zoom = 'auto';
        geo.aspectScale = 'auto';
        // 注意：当使用 left/top/right/bottom 时，不再需要 layoutCenter, layoutSize, zoom, aspectScale
      });

      chartInstance.setOption({
        geo: option.geo
      });
    }
  } else {
    // 更新所有geo配置
    const option = chartInstance.getOption();
    let mapNameToSize = {
      'beijing': '145%',
      'guangxi': '175%',
      'hubei': '175%',
      'liaoning': '175%',
      'shanxi': '125%',
      'sichuan': '175%',
      'hebei': '135%'
    };
    if (Array.isArray(option.geo)) {
      // 如果是下钻的省份地图，保留原有的布局方式
      option.geo.forEach((geo: any, index: number) => {
        geo.layoutCenter = ['51%', `${46 + index * 0.5}%`]; // 位置
        geo.layoutSize = mapNameToSize[mapName] || '140%'; // 大小 (这个变量在下钻时会被更新)
        geo.zoom = 0.65;
        geo.aspectScale = 1; // 保持省份地图的原始宽高比
      });

      chartInstance.setOption({
        geo: option.geo
      });
    }
  }
}

function resize() {
  chartInstance.resize();
  // adjustMapSize();
}

// 暴露函数 （供hook调用）
defineExpose({
  resize,
  updateChart
});

useResize();

const cleanChart = (chart) => {
  if (!chart) return;

  // 移除所有事件监听器
  chart.off('click');
  chart.off('mouseover');
  // 添加其他需要移除的事件...

  // 清除动画
  chart.clear();

  // 销毁实例
  chart.dispose();
};

// onMounted(() => {
//   adjustMapSize();
// });

onBeforeUnmount(() => {
  cleanChart(chartInstance);
});
</script>

<style scoped>
.china-map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.china-map {
  width: 100%;
  height: 100%;
}
</style>
